<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMoneyRegister;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\OrdersType;
use plugin\ycMassage\utils\enum\PayType;
use plugin\ycMassage\utils\enum\State;
use support\Request;
use think\facade\Db;

class MoneyRegisterController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->addScreen('state', 'select', '状态', [
            'options' => State::getOptions()
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addTopButton('create', '创建套餐', [
            'api'       => $this->pluginPrefix . '/admin/MoneyRegister/create',
            'path' => '/MoneyRegister/create',
            'type'      => 'modal'
        ], [
            'title' => '温馨提示',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('update', '编辑', [
            'api'    => $this->pluginPrefix . '/admin/MoneyRegister/update',
            'path' => '/MoneyRegister/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('del', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/MoneyRegister/delete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('money', '充值金额')
            ->addColumn('give_money', '赠送金额')
            ->addColumn('start_time', '开始时间')
            ->addColumn('end_time', '结束时间')
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/MoneyRegister/updateState',
                    'checked' => State::YES,
                    'unchecked' => State::NO
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['saas_appid', '=', $request->saas_appid]
        ];
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['state', '=', $state];
        }
        $data = MassageMoneyRegister::where($where)
            ->order('money asc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->nickname) {
                    $item->nickname = base64_decode($item->nickname);
                }
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $MassageMoneyRegister = new MassageMoneyRegister;
                $D['saas_appid'] = $request->saas_appid;
                if (empty($D['start_time'])) {
                    unset($D['start_time']);
                }
                if (empty($D['end_time'])) {
                    unset($D['end_time']);
                }
                $MassageMoneyRegister->save($D);
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 24,
            'options' => State::getOptions()
        ]);
        $builder->addRow('money', 'number', '充值金额', null, [
            'col' => 12,
            'props' => [
                'min' => 0,
                'controls' => false,
                'precision' => 2
            ]
        ]);
        $builder->addRow('give_money', 'number', '赠送金额', null, [
            'col' => 12,
            'props' => [
                'min' => 0,
                'controls' => false,
                'precision' => 2
            ]
        ]);
        $builder->addRow('start_time', 'datetime', '开始时间', null, [
            'col' => 12,
            'props' => [
                'format' => 'YYYY-MM-DD HH:mm:ss',
                'value-format' => 'YYYY-MM-DD HH:mm:ss'
            ]
        ]);
        $builder->addRow('end_time', 'datetime', '结束时间', null, [
            'col' => 12,
            'props' => [
                'format' => 'YYYY-MM-DD HH:mm:ss',
                'value-format' => 'YYYY-MM-DD HH:mm:ss'
            ]
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $MassageMoneyRegister = MassageMoneyRegister::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageMoneyRegister) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                if (empty($D['start_time'])) {
                    $D['start_time'] = null;
                }
                if (empty($D['end_time'])) {
                    $D['end_time'] = null;
                }
                $MassageMoneyRegister->save($D);
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 24,
            'options' => State::getOptions()
        ]);
        $builder->addRow('money', 'number', '充值金额', null, [
            'col' => 12,
            'props' => [
                'min' => 0,
                'controls' => false,
                'precision' => 2
            ]
        ]);
        $builder->addRow('give_money', 'number', '赠送金额', null, [
            'col' => 12,
            'props' => [
                'min' => 0,
                'controls' => false,
                'precision' => 2
            ]
        ]);
        $builder->addRow('start_time', 'datetime', '开始时间', null, [
            'col' => 12,
            'props' => [
                'format' => 'YYYY-MM-DD HH:mm:ss',
                'value-format' => 'YYYY-MM-DD HH:mm:ss',
            ]
        ]);
        $builder->addRow('end_time', 'datetime', '结束时间', null, [
            'col' => 12,
            'props' => [
                'format' => 'YYYY-MM-DD HH:mm:ss',
                'value-format' => 'YYYY-MM-DD HH:mm:ss'
            ]
        ]);
        $data = $builder->setData($MassageMoneyRegister)->create();
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $MassageMoneyRegister = MassageMoneyRegister::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        $MassageMoneyRegister->state = $MassageMoneyRegister->state == State::YES['value'] ? State::NO['value'] : State::YES['value'];
        if ($MassageMoneyRegister->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageMoneyRegister = MassageMoneyRegister::where($where)->find();
        if (!$MassageMoneyRegister) {
            return $this->fail('数据不存在');
        }
        if ($MassageMoneyRegister->delete()) {
            return $this->success('删除成功');
        }
        return $this->fail('删除失败');
    }
    public function ordersGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->checkboxConfig();
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('trade', 'input', '订单号');
        $builder->addScreen('state', 'select', '状态', [
            'options' => OrdersState::getOptions()
        ]);
        $builder->addScreen('start_time', 'input', '开始时间', [
            'type' => 'date'
        ]);
        $builder->addScreen('end_time', 'input', '结束时间', [
            'type' => 'date'
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Orders/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '是否确认删除所选数据',
        ], [
            'type' => 'danger',
        ]);
        $builder->addRightButton('complete', '完成', [
            'api'    => $this->pluginPrefix . '/admin/Orders/complete',
            'type'      => 'confirm',
            'method' => 'post',
            'params' => [
                'field' => 'state',
                'where' => 'in',
                'value' => [OrdersState::NOT_PAY['value'], OrdersState::PAY['value']]
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认完成订单',
        ], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('delete', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Orders/delete',
            'type'      => 'confirm',
            'method' => 'delete',
            'params' => [
                'field' => 'state',
                'where' => '=',
                'value' => OrdersState::CANCEL['value']
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('title', '充值内容', [
                'minWidth' => 200,
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumn('mobile', '手机号', [
                'width' => 160,
            ])
            ->addColumn('price', '充值金额', [
                'width' => 100,
            ])
            ->addColumn('give_price', '赠送金额', [
                'width' => 100,
            ])
            ->addColumn('trade', '订单号', [
                'minWidth' => 200,
            ])
            ->addColumnEle('pay_type', '支付方式', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => PayType::dictOptions(),
                ],
            ])
            ->addColumn('pay_time', '支付时间', [
                'width' => 160,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => OrdersState::dictOptions(),
                    'style' => OrdersState::dictOptions('style'),
                ],
            ])
            ->addColumn('create_time', '下单时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function orders(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['o.saas_appid', '=', $request->saas_appid]
        ];
        $trade = $request->get('trade');
        if ($trade) {
            $where[] = ['o.trade', 'like', '%' . $trade . '%'];
        }
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['o.uid', '=', $uid];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['o.state', '=', $state];
        }
        $start_time = $request->get('start_time');
        if ($start_time) {
            $where[] = ['o.create_time', '>=', $start_time . ' 00:00:00'];
        }
        $end_time = $request->get('end_time');
        if ($end_time) {
            $where[] = ['o.create_time', '<=', $end_time . ' 23:59:59'];
        }
        $where[] = ['o.orders_type', '=', OrdersType::MONEY['value']];
        $filed = [
            'o.*',
            'u.nickname,u.headimg,u.mobile',
        ];
        $MassageOrdersObj = MassageOrders::alias('o')->where($where);
        $MassageOrdersObj->join('MassageUser u', 'u.id=o.uid');
        $data = $MassageOrdersObj->order('o.id desc')
            ->field($filed)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->nickname) {
                    $item->nickname = base64_decode($item->nickname);
                }
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            });
        return $this->successRes($data);
    }
}
